const express = require("express");
const timecapsuleModel = require("../model/timeCapsule.js");
const router = express.Router();
const {send , sendErr} = require("./send.js");

router.get("/" , async function(req , res){
    try {
        let { key } = req.query;
        let timecapsule = await timecapsuleModel.findOne({ key });
        if (timecapsule) {
            if (Date.now() < timecapsule.openTime) send(res, {
                data: {
                    openTime: timecapsule.openTime,
                    tip: timecapsule.tip,
                    authorId: timecapsule.authorId,
                    username: timecapsule.username
                }
            })
            else send(res, {
                data: {
                    content: timecapsule.content,
                    authorId: timecapsule.authorId,
                    createAt: timecapsule.createAt,
                    username: timecapsule.username,
                    openTime: timecapsule.openTime
                }
            })
        } else send(res);
    } catch (error) {
        console.log(error);
        sendErr(res, { msg: "传入的数据可能有问题" });
    }
})

router.post("/create" , async function(req , res){
    try {
        let { authorId, username, tip, content, email, openTime } = req.body;
        function createKey() {
            let str = "1234567890qwertyuioplkjhgfdsazxcvbnm";
            let key = [];
            for (let i = 0; i < 4; i++) {
                let chunk = "";
                for(let j = 0 ; j < 4 ; j++){
                    chunk += str[Math.floor(Math.random() * str.length)];
                }
                key.push(chunk);
            }
            return key.join("-");
        }
        let key, timecapsule;
        do {
            key = createKey();
            timecapsule = await timecapsuleModel.findOne({ key });
        } while (timecapsule);
        timecapsule = await timecapsuleModel.create({
            openTime,
            username,
            email,
            content,
            tip,
            authorId,
            key
        })
        if (timecapsule) send(res, { data: key });
        else sendErr(res, { msg: "创建失败" });
    } catch (error) {
        console.log(error);
        sendErr(res, { msg: "传入的数据可能有问题" });
    }
})

module.exports = router;